/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     | Website:  https://openfoam.org
    \\  /    A nd           | Copyright (C) 2024-2025 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "multiValveEngine.H"
#include "pointDist.H"

/* * * * * * * * * * * * * Static Private Member Data  * * * * * * * * * * * */

Foam::word Foam::fvMeshMovers::multiValveEngine::pistonObject::pistonBowlName
(
    "pistonBowl"
);


// * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * * //

void Foam::fvMeshMovers::multiValveEngine::pistonObject::calculateBore()
{
    const polyBoundaryMesh& pbm = meshMover_.mesh().boundaryMesh();

    // Find the maximum and minimum coordinates of the piston patch-set
    vector pistonMax(vector::min);
    vector pistonMin(vector::max);

    forAllConstIter(labelHashSet, patchSet, iter)
    {
        const label patchi = iter.key();
        if (pbm[patchi].localPoints().size())
        {
            pistonMax = max(pistonMax, max(pbm[patchi].localPoints()));
            pistonMin = min(pistonMin, min(pbm[patchi].localPoints()));
        }
    }

    reduce(pistonMax, maxOp<point>());
    reduce(pistonMin, minOp<point>());

    // Assuming the piston moves in the positive axis direction
    // remove the axis_ component to find the lateral extent of the piston
    pistonMax = pistonMax - (axis & pistonMax)*pistonMax;
    pistonMin = pistonMin - (axis & pistonMin)*pistonMin;

    bore_ = mag(pistonMax - pistonMin)/sqrt(2.0);
    centre_ = (pistonMax + pistonMin)/2;
}


void Foam::fvMeshMovers::multiValveEngine::pistonObject::correctClearance()
{
    const polyBoundaryMesh& pbm = meshMover_.mesh().boundaryMesh();

    // Find the maximum and minimum coordinate of the liner patch-sets
    scalar linerMax(-great);
    scalar linerMin(great);

    forAllConstIter(labelHashSet, meshMover_.linerPatchSet_, iter)
    {
        const label patchi = iter.key();
        if (pbm[patchi].localPoints().size())
        {
            linerMax = max(linerMax, axis & max(pbm[patchi].localPoints()));
            linerMin = min(linerMin, axis & min(pbm[patchi].localPoints()));
        }
    }

    reduce(linerMax, maxOp<scalar>());
    reduce(linerMin, minOp<scalar>());

    clearance_ = linerMax - linerMin;
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::fvMeshMovers::multiValveEngine::pistonObject::pistonObject
(
    const word& name,
    const multiValveEngine& engine,
    const dictionary& dict
)
:
    movingObject(name, engine, dict),
    clearance_(0)
{
    calculateBore();
}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

Foam::scalar Foam::fvMeshMovers::multiValveEngine::pistonObject::bore() const
{
    return bore_;
}


Foam::vector Foam::fvMeshMovers::multiValveEngine::pistonObject::centre() const
{
    return centre_;
}


Foam::scalar Foam::fvMeshMovers::multiValveEngine::pistonObject::position
(
    const scalar theta
) const
{
    return motion_->value(theta);
}


Foam::scalar
Foam::fvMeshMovers::multiValveEngine::pistonObject::position() const
{
    return position(meshMover_.userTime());
}


Foam::scalar
Foam::fvMeshMovers::multiValveEngine::pistonObject::displacement() const
{
    return
        position(meshMover_.userTime() - meshMover_.userDeltaT())
      - position();
}


Foam::scalar Foam::fvMeshMovers::multiValveEngine::pistonObject::speed() const
{
    return displacement()/(meshMover_.mesh().time().deltaTValue() + vSmall);
}


Foam::scalar
Foam::fvMeshMovers::multiValveEngine::pistonObject::clearance() const
{
    if (mag(position() - position0_) > travelInterval_)
    {
        return clearance_;
    }
    else
    {
        // Note, valve movement is not considered as valveSet may include
        // other valves than ones related to ports. Furthermore, this value
        // is only an estimate and updated rather frequently anyway.
        return clearance_ - displacement();
    }
}


void Foam::fvMeshMovers::multiValveEngine::pistonObject::updatePoints
(
    pointField& newPoints
)
{
    const scalar position = this->position();

    // Update a cached scale_ field if needed
    if
    (
        executionCount_ == 0
     || mag(position - position0_) > travelInterval_
    )
    {
        Info << "    Updating scale field" << endl;

        const pointMesh& pMesh = pointMesh::New(meshMover_.mesh());
        const pointField& points(meshMover_.mesh().points());

        pointDist pDistMoving
        (
            pMesh,
            patchSet,
            movingPointZones(),
            staticPatchSet_,
            staticPointZones(),
            points,
            maxMotionDistance_
        );

        pointDist pDistStatic
        (
            pMesh,
            staticPatchSet_,
            staticPointZones(),
            patchSet,
            movingPointZones(),
            points,
            maxMotionDistance_
        );

        // Update the clearance from the distance to piston field
        correctClearance();

        calcScale
        (
            pMesh,
            pDistMoving,
            pDistStatic,
            movingFrozenLayerThickness_,
            maxMotionDistance_,
            staticFrozenLayerThickness_
        );

        position0_ = position;
    }

    const vector translationVector(displacement()*axis);
    transformPoints(newPoints, translationVector);
}


void Foam::fvMeshMovers::multiValveEngine::pistonObject::mapMesh
(
    const polyMeshMap& map
)
{
    movingObject::mapMesh(map);
}


// ************************************************************************* //
